package com.kcst.configure;

import android.annotation.SuppressLint;
import android.app.Application;

import java.lang.reflect.InvocationTargetException;

public final class ConfigureUtils {

    @SuppressLint("StaticFieldLeak")
    private static Application sApplication = null;

    private ConfigureUtils() {
        throw new UnsupportedOperationException("u can't instantiate me...");
    }

    /**
     * 获取全局上下文
     */
    public static Application getApp() {
        if (sApplication != null) {
            return sApplication;
        }
        return getApplicationByReflect();
    }

    private static Application getApplicationByReflect() {
        try {
            @SuppressLint("PrivateApi")
            Class<?> activityThread = Class.forName("android.app.ActivityThread");
            Object thread = activityThread.getMethod("currentActivityThread").invoke(null);
            Object app = activityThread.getMethod("getApplication").invoke(thread);
            if (app == null) {
                throw new NullPointerException("u should init first");
            }
            return (Application) app;
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException |
                 ClassNotFoundException e) {
            e.printStackTrace();
        }
        throw new NullPointerException("u should init first");
    }
}
